/**
 * 批量操作栏组件
 */

import React, { useState, useCallback } from 'react';
import {
  Trash2,
  Folder,
  X,
  AlertTriangle,
} from 'lucide-react';
import { useDocument } from '@/contexts/document';
import { showMessage } from '@/components/common/MessageTip';

interface BatchOperationBarProps {
  className?: string;
}

export default function BatchOperationBar({ className = '' }: BatchOperationBarProps) {
  const { 
    categories,
    selection,
    deleteDocuments,
    clearSelection,
    batchMoveDocuments
  } = useDocument();
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [showMoveModal, setShowMoveModal] = useState(false);
  const [selectedCategoryId, setSelectedCategoryId] = useState<string>('');
  const [isProcessing, setIsProcessing] = useState(false);

  const selectedCount = selection.selectedIds.length;

  // 清空选择
  const handleClearSelection = useCallback(() => {
    clearSelection();
  }, [clearSelection]);

  // 批量删除
  const handleBatchDelete = useCallback(async () => {
    if (selectedCount === 0) return;

    setIsProcessing(true);
    try {
      await deleteDocuments(selection.selectedIds);
      showMessage('success', `成功删除 ${selectedCount} 个文档`);
      setShowDeleteConfirm(false);
    } catch (error) {
      showMessage('error', '批量删除失败');
      console.error('Batch delete failed:', error);
    } finally {
      setIsProcessing(false);
    }
  }, [selectedCount, selection.selectedIds, deleteDocuments]);

  // 批量移动
  const handleBatchMove = useCallback(async () => {
    if (selectedCount === 0) return;

    setIsProcessing(true);
    try {
      // 确保categoryId是有效的UUID或null
      const categoryId = selectedCategoryId && selectedCategoryId.trim() !== '' ? 
        selectedCategoryId.trim() : null;
      
      // 确保documentIds是有效的UUID数组
      const validDocumentIds = selection.selectedIds
        .filter(id => id && typeof id === 'string' && id.trim() !== '');
      
      if (validDocumentIds.length === 0) {
        throw new Error('没有有效的文档ID');
      }
      
      const result = await batchMoveDocuments(validDocumentIds, categoryId);
      
      showMessage('success', `成功移动 ${result.moved_count} 个文档到指定分类`);
      setShowMoveModal(false);
      setSelectedCategoryId('');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '批量移动失败';
      showMessage('error', `批量移动失败: ${errorMessage}`);
      console.error('Batch move failed:', error);
    } finally {
      setIsProcessing(false);
    }
  }, [selectedCount, selection.selectedIds, selectedCategoryId, batchMoveDocuments]);

  // 构建分类选项
  const buildCategoryOptions = useCallback((categories: any[], level = 0): React.JSX.Element[] => {
    const options: React.JSX.Element[] = [];
    
    categories.forEach(category => {
      options.push(
        <option key={category.id} value={category.id}>
          {'  '.repeat(level)}{category.icon} {category.name}
        </option>
      );
      
      if (category.children && category.children.length > 0) {
        options.push(...buildCategoryOptions(category.children, level + 1));
      }
    });
    
    return options;
  }, []);

  if (selectedCount === 0) {
    return null;
  }

  return (
    <>
      {/* 批量操作栏 */}
      <div className={`bg-primary/10 border-t border-primary/20 px-4 py-3 flex items-center justify-between ${className}`}>
        <div className="flex items-center space-x-4">
          <span className="text-sm font-medium text-primary">
            已选择 {selectedCount} 个文档
          </span>
          <button
            onClick={handleClearSelection}
            className="text-sm text-primary hover:text-primary-hover underline"
          >
            取消选择
          </button>
        </div>

        <div className="flex items-center space-x-3">
          {/* 移动到分类 */}
          <button
            onClick={() => setShowMoveModal(true)}
            className="flex items-center px-3 py-1.5 text-sm bg-background border border-primary/30 text-primary rounded hover:bg-accent transition-colors"
          >
            <Folder className="w-4 h-4 mr-2" />
            移动到分类
          </button>

          {/* 批量删除 */}
          <button
            onClick={() => setShowDeleteConfirm(true)}
            className="flex items-center px-3 py-1.5 text-sm bg-destructive text-destructive-foreground rounded hover:bg-[hsl(var(--destructive)_/_0.8)] transition-colors"
          >
            <Trash2 className="w-4 h-4 mr-2" />
            删除
          </button>
        </div>
      </div>

      {/* 删除确认弹窗 */}
      {showDeleteConfirm && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-card rounded-lg shadow-xl w-full max-w-md">
            <div className="p-6">
              <div className="flex items-center mb-4">
                <AlertTriangle className="w-6 h-6 text-destructive mr-3" />
                <h3 className="text-lg font-semibold text-foreground">确认删除</h3>
              </div>
              
              <p className="text-sm text-muted-foreground mb-6">
                您确定要删除选中的 {selectedCount} 个文档吗？此操作不可撤销。
              </p>
              
              <div className="flex items-center justify-end space-x-3">
                <button
                  onClick={() => setShowDeleteConfirm(false)}
                  disabled={isProcessing}
                  className="px-4 py-2 text-sm border border-input text-foreground rounded hover:bg-accent disabled:opacity-50 transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={handleBatchDelete}
                  disabled={isProcessing}
                  className="px-4 py-2 text-sm bg-destructive text-destructive-foreground rounded hover:bg-[hsl(var(--destructive)_/_0.8)] disabled:opacity-50 transition-colors"
                >
                  {isProcessing ? '删除中...' : '确认删除'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 移动分类弹窗 */}
      {showMoveModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-card rounded-lg shadow-xl w-full max-w-md">
            <div className="flex items-center justify-between p-6 border-b border-border">
              <h3 className="text-lg font-semibold text-foreground">移动到分类</h3>
              <button
                onClick={() => {
                  setShowMoveModal(false);
                  setSelectedCategoryId('');
                }}
                className="w-8 h-8 flex items-center justify-center rounded hover:bg-accent transition-colors"
              >
                <X className="w-5 h-5 text-muted-foreground" />
              </button>
            </div>
            
            <div className="p-6">
              <p className="text-sm text-muted-foreground mb-4">
                选择要移动到的目标分类，将 {selectedCount} 个文档移动到指定分类中。
              </p>
              
              <div className="mb-6">
                <label className="block text-sm font-medium text-foreground mb-2">
                  目标分类
                </label>
                <select
                  value={selectedCategoryId}
                  onChange={(e) => setSelectedCategoryId(e.target.value)}
                  className="w-full border border-input rounded-lg px-3 py-2 text-sm bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
                >
                  <option value="">根目录（无分类）</option>
                  {buildCategoryOptions(categories)}
                </select>
              </div>
              
              <div className="flex items-center justify-end space-x-3">
                <button
                  onClick={() => {
                    setShowMoveModal(false);
                    setSelectedCategoryId('');
                  }}
                  disabled={isProcessing}
                  className="px-4 py-2 text-sm border border-input text-foreground rounded hover:bg-accent disabled:opacity-50 transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={handleBatchMove}
                  disabled={isProcessing}
                  className="px-4 py-2 text-sm bg-primary text-primary-foreground rounded hover:bg-primary-hover disabled:opacity-50 transition-colors"
                >
                  {isProcessing ? '移动中...' : '确认移动'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
